﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Text;
using RobozzleModel;

public partial class puzzlefeed : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
		Response.Clear();
		Response.ContentType = "text/xml";
		XmlTextWriter objX = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
		objX.WriteStartDocument();
        objX.WriteProcessingInstruction("xml-stylesheet", "type='text/css' href='http://robozzle.com/stats.css'");
		objX.WriteStartElement("rss");
        objX.WriteAttributeString("xmlns:content", "http://purl.org/rss/1.0/modules/content/");
		objX.WriteAttributeString("version","2.0");
		objX.WriteStartElement("channel");
		objX.WriteElementString("title", "RoboZZle Puzzles");
		objX.WriteElementString("link","http://robozzle.com");
		objX.WriteElementString("description","The latest puzzles for the RoboZZle online puzzle game.");
		objX.WriteElementString("copyright","(c) 2008, Igor Ostrovsky. All rights reserved.");
		objX.WriteElementString("ttl","5");

        RobozzleEntities entities = new RobozzleEntities();
        var commentCounts =
            entities.ForumComment
               .GroupBy(comment => comment.ForumThread)
               .Select(g => new { PuzzleId = g.Key.PuzzleId, Count = g.Count() })
               .Where(p => p.PuzzleId != null)
               .ToDictionary(p => p.PuzzleId);
        var solutionCounts =
            entities.Solution
               .Where(p => p.UserName != null && p.LevelId >= 0)
               .GroupBy(p => p.LevelId, p => p.UserName)
               .Select(p => new { PuzzleId = p.Key, Count = p.Distinct().Count() })
               .ToDictionary(p => p.PuzzleId, p => p.Count);

        Dictionary<string, User> users = entities.User.ToDictionary(user => user.Username);

        foreach (LevelWithDifficulty level in entities.LevelWithDifficulty.OrderByDescending(level => level.Id))
        {
            int liked = (level.CoolnessVoteSum + level.CoolnessVoteCount) / 2;
            int disliked = level.CoolnessVoteCount - liked;
            string difficulty = level.DifficultyVoteCount > 0
                ? String.Format("{0:0.00}", (1.0 * level.DifficultyVoteSum / level.DifficultyVoteCount))
                : "unrated so far";
            int commentCount = commentCounts.ContainsKey(level.Id) ? commentCounts[level.Id].Count : 0;
            string commentLink = "<a href=\"http://robozzle.com/forums/thread.aspx?puzzle=" + level.Id + "\">" + StatsCommon.Plural("comment", commentCount) + "</a>";

            int solutionCount = solutionCounts.ContainsKey(level.Id) ? solutionCounts[level.Id] : 0;
            string solutionLink = "<a href=\"http://robozzle.com/puzzle.aspx?id=" + level.Id + "\">" + StatsCommon.Plural("solution", solutionCount) + "</a>";

            string author = level.SubmittedBy == null
                ? "Anonymous"
                : string.Format("<a href='http://robozzle.com/user.aspx?name={0}'>{0}</a>", level.SubmittedBy);

            string content =
                MakeGameBoardTable(level)
                + "<p>" + solutionLink + " | " + commentLink + "</p>"
                + string.Format(
                    "<p><table border=\"0\">" +
                    "<tr><td><strong>Difficulty (1..5):</strong></td><td> {2} ({3} votes)</td></tr>" +
                    "<tr><td><strong>Popularity:</strong></td><td> {4} ({5} liked, {6} disliked)</td></tr>" +
                    "<tr><td><strong>Author:</strong></td><td> {0} </td></tr>" +
                    "<tr><td><strong>Posted:</strong></td><td>{1}</td></tr>" +
                    "</table>",
                    author,
                    level.SubmittedDate,
                    difficulty, level.DifficultyVoteCount,
                    level.CoolnessVoteSum, liked, disliked,
                    level.Id,
                    level.Solutions);

            WriteItem(
                string.Format("Puzzle {0}: {1}", level.Id, level.Title),
                string.Format("Puzzle by {0}, difficulty is {1}, liked by {2}, disliked by {3}.", 
                    level.SubmittedBy == null ? "an anonymous user" : level.SubmittedBy,
                    difficulty, liked, disliked),
                string.Format("http://robozzle.com/index.aspx?puzzle={0}", level.Id),
                level.SubmittedDate,
                content,
                objX);
        }

		objX.WriteEndElement();
		objX.WriteEndElement();
		objX.WriteEndDocument();
		objX.Flush();
		objX.Close();
		Response.End();
    }

    private static void WriteItem(string title, string description, string url, DateTime pubDate, string content, XmlTextWriter objX)
    {
        objX.WriteStartElement("item");
        objX.WriteElementString("title", title);
        objX.WriteElementString("description", description);
        objX.WriteElementString("link", url);
        objX.WriteElementString("pubDate", pubDate.ToString("R"));

        objX.WriteStartElement("content:encoded");
        objX.WriteCData(content);
        objX.WriteEndElement();


        objX.WriteEndElement();
    }

    private static string MakeGameBoardTable(LevelWithDifficulty level)
    {
        return "<a href=\"http://robozzle.com/index.aspx?puzzle=" + level.Id + "\">"
           + "<img src='http://robozzle.com/images/puzzlethumb/" + level.Id + ".png' border='1' style='border: solid 1px black'/>"
           + "</a>";
    }
}
